﻿using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using RuYiAdmin.Net.Common.Global;
using RuYiAdmin.Net.Common.Utility;
using RuYiAdmin.Net.Entity.BusinessDTO.SystemManagement;
using RuYiAdmin.Net.Entity.BusinessEntity.SystemManagement;
using RuYiAdmin.Net.Entity.BusinessEnum;
using RuYiAdmin.Net.Entity.CoreEntity;
using RuYiAdmin.Net.Entity.CoreEnum;
using RuYiAdmin.Net.Service.BusinessService.Redis;
using RuYiAdmin.Net.Service.BusinessService.SystemManagement.CodeTable;
using RuYiAdmin.Net.WebApi.AppCode.ActionFilters;
using RuYiAdmin.Net.WebApi.AppCode.FrameworkBase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace RuYiAdmin.Net.WebApi.Controllers.SystemManagement
{
    /// <summary>
    /// 数据字典管理控制器
    /// </summary>
    public class CodeTableManagementController : BaseController<SysCodeTable>
    {
        #region 属性及构造函数

        /// <summary>
        /// 数据字典接口实例
        /// </summary>
        private readonly ICodeTableService codeTableService;

        /// <summary>
        /// Redis接口实例
        /// </summary>
        private readonly IRedisService redisService;

        /// <summary>
        /// AutoMapper实例
        /// </summary>
        private readonly IMapper mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="codeTableService"></param>
        /// <param name="redisService"></param>
        /// <param name="mapper"></param>
        public CodeTableManagementController(ICodeTableService codeTableService,
                                             IRedisService redisService,
                                             IMapper mapper) : base(codeTableService)
        {
            this.codeTableService = codeTableService;
            this.redisService = redisService;
            this.mapper = mapper;
        }

        #endregion

        #region 查询字典列表

        /// <summary>
        /// 查询字典列表
        /// </summary>
        /// <param name="queryCondition">查询条件</param>
        /// <returns>ActionResult</returns>
        [HttpPost]
        [Log(OperationType.QueryList)]
        [Permission("code:query:list")]
        public IActionResult Post(QueryCondition queryCondition)
        {
            var actionResult = this.codeTableService.GetCodeTreeNodes();
            return Ok(actionResult);
        }

        #endregion

        #region 获取字典信息

        /// <summary>
        /// 获取字典信息
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns>ActionResult</returns>
        [HttpGet("{id}")]
        [Log(OperationType.QueryEntity)]
        [Permission("log:query:list")]
        public IActionResult GetById(Guid id)
        {
            var actionResult = new Entity.CoreEntity.ActionResult();

            actionResult.HttpStatusCode = HttpStatusCode.OK;
            actionResult.Message = new String("OK");
            var codes = this.redisService.Get<List<SysCodeTableDTO>>(GlobalContext.SystemCacheConfig.CodeTableCacheName);
            actionResult.Object = codes.Where(t => t.Id == id).FirstOrDefault();

            return Ok(actionResult);
        }

        #endregion

        #region 新增字典信息

        /// <summary>
        /// 新增字典信息
        /// </summary>
        /// <param name="codeTable">字典对象</param>
        /// <returns>ActionResult</returns>
        [HttpPost]
        [Log(OperationType.AddEntity)]
        [Permission("code:add:entity")]
        public IActionResult Add([FromBody] SysCodeTable codeTable)
        {
            var actionResult = this.codeTableService.Add(codeTable);

            //数据一致性维护
            var codes = this.redisService.Get<List<SysCodeTableDTO>>(GlobalContext.SystemCacheConfig.CodeTableCacheName);
            var codeTableDTO = mapper.Map<SysCodeTableDTO>(codeTable);
            codes.Add(codeTableDTO);
            this.redisService.Set(GlobalContext.SystemCacheConfig.CodeTableCacheName, codes, -1);

            return Ok(actionResult);
        }

        #endregion

        #region 修改字典信息

        /// <summary>
        /// 修改字典信息
        /// </summary>
        /// <param name="codeTable">字典对象</param>
        /// <returns>IActionResult</returns>
        [HttpPut]
        [Log(OperationType.EditEntity)]
        [Permission("code:edit:entity")]
        public IActionResult Put([FromBody] SysCodeTable codeTable)
        {
            var actionResult = this.codeTableService.Update(codeTable);

            //数据一致性维护
            var codes = this.redisService.Get<List<SysCodeTableDTO>>(GlobalContext.SystemCacheConfig.CodeTableCacheName);
            var code = codes.Where(t => t.Id == codeTable.Id).FirstOrDefault();
            codes.Remove(code);
            var codeTableDTO = mapper.Map<SysCodeTableDTO>(codeTable);
            codes.Add(codeTableDTO);
            this.redisService.Set(GlobalContext.SystemCacheConfig.CodeTableCacheName, codes, -1);

            return Ok(actionResult);
        }

        #endregion

        #region 删除字典信息

        /// <summary>
        /// 删除字典信息
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns>ActionResult</returns>
        [HttpDelete("{id}")]
        [Log(OperationType.DeleteEntity)]
        [Permission("code:del:entities")]
        public IActionResult Delete(Guid id)
        {
            if (this.Check(id))
            {
                return BadRequest("code contains subitems,can not be deleted");
            }

            var actionResult = this.codeTableService.Delete(id);

            //数据一致性维护
            var codes = this.redisService.Get<List<SysCodeTableDTO>>(GlobalContext.SystemCacheConfig.CodeTableCacheName);
            var code = codes.Where(t => t.Id == id).FirstOrDefault();
            codes.Remove(code);
            this.redisService.Set(GlobalContext.SystemCacheConfig.CodeTableCacheName, codes, -1);

            return Ok(actionResult);
        }

        #endregion

        #region 批量删除字典信息

        /// <summary>
        /// 批量删除字典信息
        /// </summary>
        /// <param name="ids">数组串</param>
        /// <returns>ActionResult</returns>
        [HttpDelete("{ids}")]
        [Log(OperationType.DeleteEntity)]
        [Permission("code:del:entities")]
        public IActionResult DeleteRange(String ids)
        {
            var array = StringUtil.GetGuids(ids);
            foreach (var item in array)
            {
                if (this.Check(item))
                {
                    return BadRequest("code contains subitems,can not be deleted");
                }
            }

            var actionResult = this.codeTableService.DeleteRange(array);

            //数据一致性维护
            var codes = this.redisService.Get<List<SysCodeTableDTO>>(GlobalContext.SystemCacheConfig.CodeTableCacheName);
            foreach (var item in array)
            {
                var code = codes.Where(t => t.Id == item).FirstOrDefault();
                codes.Remove(code);
            }
            this.redisService.Set(GlobalContext.SystemCacheConfig.CodeTableCacheName, codes, -1);

            return Ok(actionResult);
        }

        #endregion

        #region 获取字典子集

        /// <summary>
        /// 获取字典子集
        /// </summary>
        /// <param name="code">字典编码</param>
        /// <returns>ActionResult</returns>
        [HttpGet("{code}")]
        [Log(OperationType.QueryList)]
        //[Permission("code:query:list")]
        public IActionResult GetChildrenByCode(String code)
        {
            var actionResult = new Entity.CoreEntity.ActionResult();

            var codes = this.redisService.Get<List<SysCodeTableDTO>>(GlobalContext.SystemCacheConfig.CodeTableCacheName);
            var root = codes.Where(t => t.Code.Equals(code)).FirstOrDefault();

            if (root != null)
            {
                actionResult.HttpStatusCode = HttpStatusCode.OK;
                actionResult.Message = new String("OK");
                actionResult.Object = codes.Where(t => t.ParentId.Equals(root.Id)).OrderBy(t => t.Order).ToList();
            }
            else
            {
                actionResult.HttpStatusCode = HttpStatusCode.OK;
                actionResult.Message = new String("OK");
                actionResult.Object = null;
            }

            return Ok(actionResult);
        }

        #endregion

        #region 字典删除检测

        /// <summary>
        /// 字典删除检测
        /// </summary>
        /// <param name="parentId">父键</param>
        /// <returns>真假值</returns>
        private bool Check(Guid parentId)
        {
            var codes = this.redisService.Get<List<SysCodeTableDTO>>(GlobalContext.SystemCacheConfig.CodeTableCacheName);
            var sysCodes = codes.Where(t => t.ParentId == parentId).ToList();

            if (sysCodes.Count > 0)
            {
                return true;
            }

            return false;
        }

        #endregion
    }
}
